package com.example.pagergallery

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.navigation.findNavController
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import io.supercharge.shimmerlayout.ShimmerLayout
import kotlinx.coroutines.processNextEventInCurrentThread

class GalleryAdapter(val galleryViewModel: GalleryViewModel):ListAdapter<PhotoItem,MyViewHolder>(DIFFCALLBACK) {   //创建适配器时  将ViewModel传递进来
    //创建一个类的常量，类似java中的静态域
    companion object{
        const val NORMAL_VIEW_TYPE = 0
        const val FOOTER_VIEW_TYPE = 1
    }
    var footerViewStatus = DATA_STATUS_CAN_LOAD_MORE

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val holder : MyViewHolder
        if(viewType == NORMAL_VIEW_TYPE){
            holder = MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.galley_cell,parent,false))
            holder.itemView.setOnClickListener {
                Bundle().apply {
                    putParcelableArrayList("PHOTO_LIST",ArrayList(currentList))   //创建一个ArrayList放入Bundle
                    putInt("PHOTO_POSITION",holder.adapterPosition)   //当前你点击的是第几个图片  将当前点中的图片在适配器中的位置传递过去
                    holder.itemView.findNavController().navigate(R.id.action_galleryFragment_to_pagerPhotoFragment,this)
                }
            }
        }else{
            holder = MyViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.gallery_footer,
                    parent,
                    false
                ).also {
                    (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan = true   //类型转换，不再分列，而是占据整个空间（加载更多）
                    it.setOnClickListener{  itemView ->  //监听点击文字时重新访问（网络错误，点击重试）
                        it.findViewById<ProgressBar>(R.id.progressBar).visibility = View.VISIBLE
                        it.findViewById<TextView>(R.id.textView).text = "正在加载"
                        galleryViewModel.fetchData()
                    }
                }
            )
        }
        return holder
    }

    override fun getItemViewType(position: Int): Int {
        return if(position == itemCount - 1) FOOTER_VIEW_TYPE else NORMAL_VIEW_TYPE  //itemCount - 1 指最后一行
    }

    //返回的缺省值加一（因为底部要多加一个，加载更多）
    override fun getItemCount(): Int {
        return super.getItemCount() + 1
    }

    //绑定组件
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val progressBar = holder.itemView.findViewById<ProgressBar>(R.id.progressBar)
        val textView = holder.itemView.findViewById<TextView>(R.id.textView)
        if (position == itemCount - 1) {
            with(holder.itemView){
                when(footerViewStatus){    //监听三种状态
                    DATA_STATUS_CAN_LOAD_MORE -> {
                        progressBar.visibility = View.VISIBLE
                        textView.text = "正在加载"
                        isClickable = false
                    }
                    DATA_STATUS_NO_MORE -> {
                        progressBar.visibility = View.GONE
                        textView.text = "全部加载完毕"
                        isClickable = false
                    }
                    DATA_STATUS_NETWORK_ERROR -> {
                        progressBar.visibility = View.GONE
                        textView.text = "网络错误，点击重试"
                        isClickable = true   //可以被点击
                    }
                }
            }
            return
        }
        val photoItem = getItem(position)
        val shimmerLayout = holder.itemView.findViewById<ShimmerLayout>(R.id.shimmerLayoutCell)
        with(holder.itemView){
            shimmerLayout.apply {
                setShimmerColor(0x55FFFFFF)
                setShimmerAngle(0)
                startShimmerAnimation()
            }
            holder.itemView.findViewById<TextView>(R.id.textViewUser).text = photoItem.photoUser
            holder.itemView.findViewById<TextView>(R.id.textViewViews).text = photoItem.photoViews.toString()
            holder.itemView.findViewById<TextView>(R.id.textViewLikes).text = photoItem.photoLikes.toString()
            holder.itemView.findViewById<TextView>(R.id.textViewId).text = photoItem.photoId.toString()
            holder.itemView.findViewById<ImageView>(R.id.imageView).layoutParams.height = photoItem.photoHeight   //取回当前图片对象以及图片高度
        }

        Glide.with(holder.itemView)
            .load(getItem(position).previewUrl)
            .placeholder(R.drawable.photo_placeholder)
            .listener(object :RequestListener<Drawable>{
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also { holder.itemView.findViewById<ShimmerLayout>(R.id.shimmerLayoutCell)?.stopShimmerAnimation() }
                }

            })
            .into(holder.itemView.findViewById(R.id.imageView))
    }



    object DIFFCALLBACK:DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem.photoId == newItem.photoId
        }

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem == newItem
        }
    }


}

class MyViewHolder(itemView: View) :RecyclerView.ViewHolder(itemView)